<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属班级" prop="belongId">
            <el-tree-select
                v-model="queryParams.belongId"
                :data="classOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择班级"
                check-strictly
                default-expand-all
            />
          </el-form-item>
          <el-form-item label="住宿类型" prop="accommodationType">
            <el-select v-model="queryParams.accommodationType" placeholder="请选择住宿类型" clearable>
              <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学号" prop="studentNo">
            <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
              <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="打卡类型" prop="punchType">
            <el-select v-model="queryParams.punchType" placeholder="请选择打卡类型" clearable>
              <el-option v-for="dict in sg_punch_type" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
          <el-form-item label="打卡时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangePunchTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 420px)" stripe v-loading="loading" :data="studentAttendanceRecordList" @selection-change="handleSelectionChange">
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="住宿类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="student_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="所属班级" align="center" prop="className" />
        <el-table-column label="学号" align="center" prop="studentNo" />
        <el-table-column label="人员状态" align="center" prop="studentStatus">
          <template #default="scope">
            <dict-tag :options="student_school_status" :value="scope.row.studentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="打卡时间" align="center" prop="punchTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.punchTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备" align="center" prop="deviceName" />
        <el-table-column label="抓拍图" align="center" prop="snapshotPic" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.snapshotPic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="人脸图" align="center" prop="facePic" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.facePic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="比对分值" align="center" prop="comparisonScore" />
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生考勤记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="studentAttendanceRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生id" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生id" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="班级id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入班级id" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="打卡时间" prop="punchTime">
          <el-date-picker clearable v-model="form.punchTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择打卡时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="图片路径" prop="facePic">
          <el-input v-model="form.facePic" placeholder="请输入图片路径" />
        </el-form-item>
        <el-form-item label="抓拍图" prop="snapshotPic">
          <el-input v-model="form.snapshotPic" placeholder="请输入抓拍图" />
        </el-form-item>
        <el-form-item label="比对分值" prop="comparisonScore">
          <el-input v-model="form.comparisonScore" placeholder="请输入比对分值" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudentAttendanceRecord" lang="ts">
import {
  listStudentAttendanceRecord,
  getStudentAttendanceRecord,
  delStudentAttendanceRecord,
  addStudentAttendanceRecord,
  updateStudentAttendanceRecord
} from '@/api/attendance/student/record';
import { StudentAttendanceRecordVO, StudentAttendanceRecordQuery, StudentAttendanceRecordForm } from '@/api/attendance/student/record/types';
import { classTree, listClassInfo } from '@/api/office/class';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  student_accommodation_type,
  student_sex,
  student_subscribe_status,
  student_school_status,
  faculty_type,
  face_pic_status,
  student_guardian_relation,
  device_type,
  sg_punch_type
} = toRefs<any>(
  proxy?.useDict(
    'student_accommodation_type',
    'student_sex',
    'student_subscribe_status',
    'student_school_status',
    'faculty_type',
    'face_pic_status',
    'student_guardian_relation',
    'device_type',
    'sg_punch_type'
  )
);
const studentAttendanceRecordList = ref<StudentAttendanceRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangePunchTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const studentAttendanceRecordFormRef = ref<ElFormInstance>();
const classOptions = ref<any[]>([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StudentAttendanceRecordForm = {
  id: undefined,
  studentId: undefined,
  studentName: undefined,
  gender: undefined,
  classId: undefined,
  className: undefined,
  studentNo: undefined,
  studentStatus: undefined,
  accommodationType: undefined,
  punchTime: undefined,
  deviceType: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  facePic: undefined,
  snapshotPic: undefined,
  comparisonScore: undefined
};
const data = reactive<PageData<StudentAttendanceRecordForm, StudentAttendanceRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    studentName: undefined,
    gender: undefined,
    classId: undefined,
    className: undefined,
    studentNo: undefined,
    studentStatus: undefined,
    accommodationType: undefined,
    punchType: undefined,
    punchTime: undefined,
    deviceType: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    facePic: undefined,
    snapshotPic: undefined,
    comparisonScore: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
    studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    studentNo: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    studentStatus: [{ required: true, message: '学生状态不能为空', trigger: 'change' }],
    accommodationType: [{ required: true, message: '住宿类型不能为空', trigger: 'change' }],
    punchTime: [{ required: true, message: '打卡时间不能为空', trigger: 'blur' }],
    deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    facePic: [{ required: true, message: '图片路径不能为空', trigger: 'blur' }],
    snapshotPic: [{ required: true, message: '抓拍图不能为空', trigger: 'blur' }],
    comparisonScore: [{ required: true, message: '比对分值不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const getClassTree = async () => {
  const res = await classTree();
  classOptions.value = res.data;
};

/** 查询学生考勤记录列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangePunchTime.value, 'PunchTime');
  const res = await listStudentAttendanceRecord(queryParams.value);
  studentAttendanceRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentAttendanceRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangePunchTime.value = ['', ''];
  queryParams.value.classId = undefined;
  queryParams.value.className = undefined;
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentAttendanceRecordVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加学生考勤记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentAttendanceRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStudentAttendanceRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改学生考勤记录';
};

/** 提交按钮 */
const submitForm = () => {
  studentAttendanceRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStudentAttendanceRecord(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addStudentAttendanceRecord(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentAttendanceRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除学生考勤记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delStudentAttendanceRecord(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/studentAttendanceRecord/export',
    {
      ...queryParams.value
    },
    `studentAttendanceRecord_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getClassTree();
  getList();
});
</script>
